//
//  JCCreatClubTVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/20.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCCreatClubTVC.h"
#import "JCClubApi.h"
#import "WSProgressHUD.h"
#import "SystemSelectPhotoManager.h"
#import "SQActionSheetView.h"
#import <Qiniu/QiniuSDK.h>
#import "UIImage+HXExtension.h"
#import "YFBaseRequest.h"
#import "YFMomentApi.h"
#import "YFAlertHelper.h"
#import "JCClubGetCodeCallView.h"
#import "ClubsSetting.h"
#import "PhotoActionSheetViewController.h"

#define kHeightFold                 75
#define kCodeHeightUnFold           224
#define kImformationHeightUnFold    234
#define kPicturesHeightUnFold       403
#define kContactHeightUnFold        311

@interface JCCreatClubTVC ()
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (assign, nonatomic) NSInteger codeCellHeight;
@property (assign, nonatomic) NSInteger imformationCellHeight;
@property (assign, nonatomic) NSInteger picturesCellHeight;
@property (assign, nonatomic) NSInteger contactCellHeight;

@property (weak, nonatomic) IBOutlet UIButton *codeCellButton;
@property (weak, nonatomic) IBOutlet UIButton *codeCellButton2;
@property (weak, nonatomic) IBOutlet UITextField *codeInput;

@property (weak, nonatomic) IBOutlet UIButton *informationCellButton;
@property (weak, nonatomic) IBOutlet UIButton *informationCellButton2;
@property (weak, nonatomic) IBOutlet UITextField *nameInput;
@property (weak, nonatomic) IBOutlet UITextField *descriptionInput;

@property (weak, nonatomic) IBOutlet UIButton *pictureCellButton;
@property (weak, nonatomic) IBOutlet UIButton *pictureCellButton2;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (strong, nonatomic) UIImage *headerImage;
@property (strong, nonatomic) UIImage *coverImage;
@property (strong, nonatomic) NSString *headerURL;
@property (strong, nonatomic) NSString *coverURL;
@property (assign, nonatomic) ImageChoiseType imageType;
@property (strong, nonatomic) SystemSelectPhotoManager *photoManger;

@property (weak, nonatomic) IBOutlet UIButton *contactCellButton;
@property (weak, nonatomic) IBOutlet UIButton *contactCellButton2;
@property (weak, nonatomic) IBOutlet UITextField *addressInput;
@property (weak, nonatomic) IBOutlet UITextField *clubPhoneInput;
@property (weak, nonatomic) IBOutlet UITextField *personalPhoneInput;

@property (strong, nonatomic) WSProgressHUD *hud;

@end

@implementation JCCreatClubTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self foldAction:_codeCellButton];
    });
}

- (void)initCode{
    self.navigationItem.title = @"Create Club";
    _submitButton.layer.cornerRadius = 3;
    _submitButton.layer.masksToBounds = YES;
    
    _codeCellHeight =
    _imformationCellHeight =
    _picturesCellHeight =
    _contactCellHeight = kHeightFold;
    
    _codeInput.attributedPlaceholder = [self creatAttributedString:@"Fill in code" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _nameInput.attributedPlaceholder = [self creatAttributedString:@"Within 50 letters" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _descriptionInput.attributedPlaceholder = [self creatAttributedString:@"Within 150 letters" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _addressInput.attributedPlaceholder = [self creatAttributedString:@"Fill in address" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _clubPhoneInput.attributedPlaceholder = [self creatAttributedString:@"Fill in number" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _personalPhoneInput.attributedPlaceholder = [self creatAttributedString:@"Fill in number" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
}

- (NSAttributedString *)creatAttributedString:(NSString *)contentString
                                         font:(UIFont *)font
                                        color:(UIColor *)color{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    attrs[NSForegroundColorAttributeName] = color;
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:contentString attributes:attrs];
    return attStr;
}

- (IBAction)getCodeFromOfficial:(UIButton *)sender {
    JCClubGetCodeCallView *alertView = [[UINib nibWithNibName:@"JCClubGetCodeCallView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    alertView.callNumber = kGetCodeOfficialNumber;
    PopupViewController *popVC = [YFAlertHelper showPresentInView:nil alertView:alertView withAlertViewFrame:CGRectMake(0, 0, 281, 164) animationType:DetailViewControllerPresentAnimationTypeDown tapMaskViewDismiss:YES];
    __weak typeof(popVC)weakPopVC = popVC;
    alertView.callHandle = ^(void) {
        [weakPopVC dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",kGetCodeOfficialNumber]]];
    };
}

- (IBAction)headerAction:(UITapGestureRecognizer *)sender {
    [self selectImage:ImageChoiseTypeHeader];
}

- (IBAction)coverAction:(UITapGestureRecognizer *)sender {
    [self selectImage:ImageChoiseTypeCover];
}

- (void)selectImage:(ImageChoiseType)type{
    self.imageType = type;
    [PhotoActionSheetViewController showInParentViewController:[[UIApplication sharedApplication] keyWindow].rootViewController alertType:UIAlertControllerStyleAlert animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        [self gotoSeletePhotoOrTakePhoto:btnType selectImage:type];
    }].isTapCoverViewDismiss = YES;
}

- (void)gotoSeletePhotoOrTakePhoto:(kTapActionButtonType)buttonType selectImage:(ImageChoiseType)selectType{
    __weak typeof(self)weakSelf = self;
    SystemSelectPhotoManager *photoManger = [SystemSelectPhotoManager selectPhotoManagerWithEditCaseType:kSystemDeflaut];
    self.photoManger = photoManger;
    [photoManger takePhotoBySource:buttonType canEdit:YES parentViewController:self selectCallBlock:^(UIImage *selectImage, NSError *error) {
        if (weakSelf.imageType == ImageChoiseTypeHeader) {
            
            weakSelf.headerImage = selectImage;
            weakSelf.headImageView.image = selectImage;
        }else if (weakSelf.imageType == ImageChoiseTypeCover){
            
            weakSelf.coverImage = selectImage;
            weakSelf.coverImageView.image = selectImage;
        }
    }];
}

- (IBAction)submitAction:(UIButton *)sender {
    if ([self checkInfoValid]) {
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        __weak typeof(self)weakSelf = self;
        [self uploadImagesQNComplated:^(NSArray *imageUrlArr, NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                weakSelf.headerURL = imageUrlArr.firstObject;
                weakSelf.coverURL = imageUrlArr.lastObject;
                [JCClubApi creatClubCode:weakSelf.codeInput.text
                                    name:weakSelf.nameInput.text
                                describe:weakSelf.descriptionInput.text
                                  banner:weakSelf.coverURL
                              headerIcon:weakSelf.headerURL
                                 address:weakSelf.addressInput.text
                               clubPhone:weakSelf.clubPhoneInput.text
                           personalPhone:weakSelf.personalPhoneInput.text
                                complete:^(NSError *error, BOOL isSuccess) {
                                    if (error) {
                                        [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                                    }else{
                                        [weakSelf.hud showSuccessWithStatus:@"Success!" dimissAfterSecond:2];
                                        [YFUserDefaults saveClubMeRefreshState:YES];
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            [self.navigationController popViewControllerAnimated:YES];
                                        });
                                    }
                                }];
            }
        }];
    }
}

- (void)uploadImagesQNComplated:(void(^)(NSArray *imageUrlArr,NSError *error))completedBlock {
    
    __weak typeof(self) weakSelf = self;
    
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi requestApiWithType:kGetQiNiuUploadImageToMomentApi andParam:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success == NO) {
            if (completedBlock) {
                completedBlock(nil,[NSError errorWithDomain:@"获取七牛token失败" code:-1001 userInfo:nil]);
            }
            return;
        }else {
            NSString *token = [[result responseInfo] objectForKey:@"token"];
            QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                //                [weakSelf.hud showProgress:percent];
            }];
            NSArray *images = @[self.headerImage,self.coverImage];
            [weakSelf upladToQNImages:images atIndex:0 token:token keys:[NSMutableArray array] filenamesArr:[NSMutableArray arrayWithCapacity:images.count] option:option completed:^(BOOL success, NSMutableArray *fileNameArr) {
                if (success) {
                    if (fileNameArr.count == 2) {
                        NSMutableArray *arrM = [NSMutableArray array];
                        [fileNameArr enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            [arrM addObject:[NSString stringWithFormat:@"%@%@",kImageBaseUrl,obj]];
                        }];
                        if (completedBlock) {
                            completedBlock(arrM.copy,nil);
                        }
                    }
                }else {
                    if (completedBlock) {
                        
                        completedBlock(nil,[NSError errorWithDomain:NSLocalizedString(@"Upload picture failed", @"上传图片失败") code:-1002 userInfo:nil]);
                    }
                }
            }];
        }
    }];
}

- (void)upladToQNImages:(NSArray <UIImage *>*)images
                atIndex:(NSInteger)index
                  token:(NSString *)token
                   keys:(NSMutableArray *)keys
           filenamesArr:(NSMutableArray *)filenamesArr
                 option:(QNUploadOption *)option
              completed:(void(^)(BOOL success,NSMutableArray *fileNameArr))completedBlock {
    
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    NSData *data = [image compressToDataHX];
    
    
    NSTimeInterval time= [[NSDate date] timeIntervalSince1970];
    
    //拼接图片上传后的路径： http://staticapp.coollang.com/bq/club/+ uuid + 下划线 + 时间戳 + 下划线 + 序号 + 中划线 + 图片宽*图片高 + .jpg
    NSString *filename = [NSString stringWithFormat:@"bq/club/%@_%.f_%ld-%d*%d.%@",[User getLastUser].userID,time,(long)imageIndex,(int)image.size.width,(int)image.size.height,@"jpg"];
    [filenamesArr addObject:filename];
    
    [[YFNetworkingService qNUploadManager] putData:data key:filename token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.isOK) {
            [keys addObject:key];
            YFLog(@"idInex %ld,OK",(long)index);
            imageIndex++;
            YFLog(@"上传完成,%@",filename);
            for (NSString *imgKey in keys) {
                NSLog(@"%@",imgKey);
            }
            if (completedBlock) {
                completedBlock(YES,filenamesArr);
            }
            if (index == 1) {
                return ;
            }
            [self upladToQNImages:images atIndex:imageIndex token:token keys:keys filenamesArr:filenamesArr option:option completed:completedBlock];
        }else{
            if (completedBlock) {
                completedBlock(NO,nil);
            }
            YFLog(@"上传失败,%@",filename);
        }
    } option:option];
}

- (BOOL)checkInfoValid{
    if (_codeInput.text.length != 8) {//NSLocalizedString(@"", @"")
        [self showAlertTitle:nil message:NSLocalizedString(@"Please input valid invitation code", @"请输入有效的邀请码")];
        return NO;
    }else if (_nameInput.text.length > 30){
        [self showAlertTitle:nil message:NSLocalizedString(@"Name within 30 words", @"名字限制在30字以内")];
        return NO;
    }else if (_descriptionInput.text.length > 100){
        [self showAlertTitle:nil message:NSLocalizedString(@"Description within 100 words", @"描述限制在100字以内")];
        return NO;
    }else if (_headerImage == nil){
        [self showAlertTitle:nil message:NSLocalizedString(@"Miss the picture", @"缺少头像")];
        return NO;
    }else if (_coverImage == nil){
        [self showAlertTitle:nil message:NSLocalizedString(@"Miss the cover", @"缺少封面")];
        return NO;
    }else if (_addressInput.text.length == 0){
        [self showAlertTitle:nil message:NSLocalizedString(@"Please enter valid address", @"请输入地址")];
        return NO;
    }else if (_clubPhoneInput.text.length > 20){
        [self showAlertTitle:nil message:NSLocalizedString(@"Please enter valid CLUB telephone", @"请输入有效CLUB电话")];
        return NO;
    }else if (_personalPhoneInput.text.length > 20){
        [self showAlertTitle:nil message:NSLocalizedString(@"Please enter valid PERSONAL mobile", @"请输入有效PERSONAL电话")];
        return NO;
    }
    return YES;
}

- (void)showAlertTitle:(NSString *)titel message:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:titel message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *done = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:done];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
//    return 0;
//}


//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return _cellArray[indexPath.section];
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return _codeCellHeight;
    }else if (indexPath.section == 1) {
        return _imformationCellHeight;
    }else if (indexPath.section == 2) {
        return _picturesCellHeight;
    }else if (indexPath.section == 3) {
        return _contactCellHeight;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 3) {
        return 0;
    }else{
        return 7;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *foot = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"creatClubFoot"];
    if (foot == nil) {
        foot = [UIView new];
        foot.backgroundColor = [UIColor clearColor];
    }
    return foot;
}

- (IBAction)foldAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    BOOL isFold = !sender.selected;
    if (sender.tag == _codeCellButton.tag) {
        if (isFold) {
            _codeCellHeight = kHeightFold;
        }else{
            _codeCellHeight = kCodeHeightUnFold;
        }
        if (sender == _codeCellButton) {
            _codeCellButton2.selected = sender.selected;
        }else{
            _codeCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _informationCellButton.tag) {
        if (isFold) {
            _imformationCellHeight = kHeightFold;
        }else{
            _imformationCellHeight = kImformationHeightUnFold;
        }
        if (sender == _informationCellButton) {
            _informationCellButton2.selected = sender.selected;
        }else{
            _informationCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _pictureCellButton.tag) {
        if (isFold) {
            _picturesCellHeight = kHeightFold;
        }else{
            _picturesCellHeight = kPicturesHeightUnFold;
        }
        if (sender == _pictureCellButton) {
            _pictureCellButton2.selected= sender.selected;
        }else{
            _pictureCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _contactCellButton.tag) {
        if (isFold) {
            _contactCellHeight = kHeightFold;
        }else{
            _contactCellHeight = kContactHeightUnFold;
        }
        if (sender == _contactCellButton) {
            _contactCellButton2.selected = sender.selected;
        }else{
            _contactCellButton.selected = sender.selected;
        }
    }
    [self.view endEditing:YES];
    [UIView performWithoutAnimation:^{
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:sender.tag]] withRowAnimation:UITableViewRowAnimationNone];
    }];
//    [self.tableView beginUpdates];
//    [self.tableView reloadData];
//    [self.tableView endUpdates];
}

- (WSProgressHUD *)hud{
    if (_hud == nil) {
        _hud = [WSProgressHUD showOnView:self.view andString:@""];
        [_hud showWithMaskType:WSProgressHUDMaskTypeGradient];
        [_hud dismiss];
    }
    return _hud;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
